package org.qiyu.live.web.starter.error;

import jakarta.servlet.http.HttpServletRequest;
import org.qiyu.live.common.interfaces.vo.WebResponseVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created with IntelliJ IDEA.
 * Description: 定义全局异常处理器
 * 针对不同的异常,返回不同的WebResponseVO
 * User: sfx
 * Date: 2023-10-22
 * Time: 18:55
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    // 记录错误日志
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    // 捕获系统异常,统一返回WebResponseVO
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public WebResponseVO sysExceptionHandler(HttpServletRequest request, Exception e) {
        logger.error("request uri is {} exception is {}", request.getRequestURI(), e);
        return WebResponseVO.sysError("系统异常");
    }

    // 捕获自定义异常,统一返回WebResponseVO
    @ExceptionHandler(QiYuErrorException.class)
    @ResponseBody
    public WebResponseVO customExceptionHandler(HttpServletRequest request, QiYuErrorException e) {
        logger.error("request uri is {} exception is {}", request.getRequestURI(), e);
        return WebResponseVO.bizError(e.getErrorMsg(), e.getErrorCode());
    }
}